import json

import requests
from retry import retry


@retry(tries=10, delay=10, backoff=1)
def finance_stocks(code_list):
    return finance_diag_score_to_code_list(code_list)


def finance_diag_score_to_code_list(code_list):
    code_fin_list = list()
    for code in code_list:
        score = finance_diag_newest_score(code)
        if score is not None and score >= 70:
            code_fin_list.append(code)
    return code_fin_list


def finance_diag_dates(symbol):
    url = 'https://bd-write.eastmoney.com/bd-write-api/dataapi/security/dates'
    data = {"secCode": symbol}
    headers = {
        "appKey": "9c8c00ce472644eab05551328d2bd96e",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"}
    response = requests.post(url=url, headers=headers, json=data)
    jd = json.loads(response.text)
    if jd['data'] is None:
        return None
    return jd['data']['reportDates']


def finance_diag(symbol, finance_report_date):
    url = 'https://bd-write.eastmoney.com/bd-write-api/dataapi/group/FINANCE_EXAMINATION_STOCK_FINCONDITION'
    headers = {
        "appKey": "9c8c00ce472644eab05551328d2bd96e",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"}
    data = {"REPORT_DATE": finance_report_date, "SEC_CODE": symbol, "ABILITY_TYPE_CASH": "现金流",
            "ABILITY_TYPE_GROWTH": "成长能力", "ABILITY_TYPE_OPERATING": "营运能力", "ABILITY_TYPE_PROFIT": "盈利能力",
            "ABILITY_TYPE_SOLVENCY": "偿债能力"}
    response = requests.post(url=url, headers=headers, json=data)
    jd = json.loads(response.text)
    return jd['data']


def finance_diag_newest_score_more_than(symbol, score):
    score_newest = finance_diag_newest_score(symbol)
    if score_newest is not None and score_newest >= score:
        return True
    return False


def finance_diag_newest_score(symbol):
    report_dates = finance_diag_dates(symbol)
    if report_dates is None:
        return None
    return finance_diag_score(symbol, report_dates[0])


def finance_diag_score(symbol, finance_report_date):
    jd = finance_diag(symbol, finance_report_date)
    if 'X_TOTAL_SCORE' not in jd['STOCK_GENFIN_RANK'][0]:
        return 0
    return jd['STOCK_GENFIN_RANK'][0]['X_TOTAL_SCORE']
